// 定义 key 处理策略的枚举类型
export enum KeyPolicy {
    NONE = "NONE",
    TO_LOWER_CASE = "TO_LOWER_CASE",
    TO_UPPER_CASE = "TO_UPPER_CASE"
}

export default class LaunchParam {
    // 私有静态属性，存储单例实例
    private static instance: LaunchParam;

    // 私有构造函数，防止外部实例化
    private constructor() { }
    private _launchParam: { [key: string]: string };
    // 静态方法，获取单例实例
    public static Inst(): LaunchParam {
        if (!LaunchParam.instance) {
            LaunchParam.instance = new LaunchParam();
            LaunchParam.instance._launchParam = LaunchParam.instance.GetUrlQueryParam(KeyPolicy.TO_LOWER_CASE);
        }
        return LaunchParam.instance;
    }
    get LaunchParam() {
        return this._launchParam;
    }

    /**
   * 取得url地址上的参数
   * @param keyPolicy key的处理方式，NONE为不处理，TO_LOWER_CASE 为所有key 都小写，TO_UPPER_CASE为所有key 都大写
   * @param fromUrl 来源url, 若不存在，默认window.location.search
   */
    public GetUrlQueryParam(keyPolicy: KeyPolicy = KeyPolicy.NONE, fromUrl?: string | URL): { [key: string]: string } {
        let search: string;
        // 根据 fromUrl 获取 search 参数
        if (fromUrl) {
            if (fromUrl instanceof URL) {
                search = fromUrl.search;
            } else {
                try {
                    const u = new URL(fromUrl);
                    search = u.search;
                } catch (error) {
                    console.error('Invalid URL provided:', error);
                    return {};
                }
            }
        } else {
            search = window.location.search;
        }

        let link = '';
        // 处理 search 为空时的 hash 情况
        if (!search) {
            const hash = window.location.hash;
            link = hash.substring(hash.lastIndexOf('#/?') + 3);
        } else {
            link = search.substring(search.lastIndexOf('?') + 1);
        }

        const param = link.split('&');
        const tmp: { [key: string]: string } = {};

        // 遍历参数并根据 keyPolicy 处理
        for (const paramItem of param) {
            const [key, value] = paramItem.split('=');
            if (key === undefined) continue;

            let processedKey = key;
            switch (keyPolicy) {
                case KeyPolicy.TO_LOWER_CASE:
                    processedKey = key.toLowerCase();
                    break;
                case KeyPolicy.TO_UPPER_CASE:
                    processedKey = key.toUpperCase();
                    break;
            }
            tmp[processedKey] = value || '';
        }

        return tmp;
    }

}